package cn.edu.swu.lxy.rolems.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import cn.edu.swu.lxy.rolems.R
import cn.edu.swu.lxy.rolems.fragment.RolesFragment
import cn.edu.swu.lxy.rolems.fragment.OnlineFragment
import cn.edu.swu.lxy.rolems.fragment.MusicFragment
import cn.edu.swu.lxy.rolems.fragment.LoveFragment
import cn.edu.swu.lxy.rolems.MyDatabaseHelperRole

class MainActivity : AppCompatActivity() {
    val dbHelper: MyDatabaseHelperRole = MyDatabaseHelperRole(this, "Roles.db", 2)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initBottomBar()
        initDatabase()
        changeIndex(0)
    }

    private fun initDatabase() {
        dbHelper.writableDatabase
        Log.d("initDB", "dbcreate")
    }

    private val fragments: List<Fragment> = listOf<Fragment>(RolesFragment(), LoveFragment(), OnlineFragment(), MusicFragment())

    private fun initBottomBar() {
        val main_bottom_bar = findViewById<LinearLayout>(R.id.main_bottom_bar)
        for (i in 0 until main_bottom_bar.childCount){
            main_bottom_bar.getChildAt(i).setOnClickListener(){
                    View -> changeIndex(i)
            }
        }
    }

    private fun changeIndex(index: Int) {
        val main_bottom_bar = findViewById<LinearLayout>(R.id.main_bottom_bar)
        for (i in 0 until main_bottom_bar.childCount){
            val child = main_bottom_bar.getChildAt(i)
            if (i == index){
                setEnable(child, false)
            }else{
                setEnable(child, true)
            }
        }
        supportFragmentManager.beginTransaction().replace(R.id.main_content, fragments[index]).commit()
    }

    private fun setEnable(child: View, isEnable: Boolean) {
        child.isEnabled = isEnable
        if (child is ViewGroup){
            for (i in 0 until child.childCount){
                child.getChildAt(i).isEnabled = isEnable
            }
        }
    }
}